﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Data;

using ISS.CaseStudy.BLL;
using ISS.CaseStudy.Entities;

namespace CaseStudy.AdminPortal
{
    public partial class RelatedInfoDetail : System.Web.UI.Page
    {
        private string id = string.Empty;
        private bool isEdit = false;
        private bool isNew = true;
        private string mode = string.Empty;

        protected void Page_Load(object sender, EventArgs e)
        {
            loginInfo.Login();

            string function = string.Format("ShowHide('{0}','{1}');", "divCategory", "divCaseStudy");
            chkGlobal.Attributes.Add("onclick", function);

            if (Request.QueryString["mode"] != null)
                mode = Request.QueryString["mode"].ToLower();

            if (Request.QueryString["id"] != null)
            {
                id = Request.QueryString["id"];
                isNew = false;

                if (!IsPostBack)
                {
                    BindData();

                    if (Request.QueryString["from"] != null)
                    {
                        divReminding.InnerHtml = "创建相关信息成功！";
                        divReminding.Visible = true;
                        divReminding.Style.Add("color", "Green");
                    }
                }

                if (mode.Equals("edit"))
                {
                    isEdit = true;
                    currentMapItem.InnerText = "编辑相关信息";
                }
                else
                {
                    isEdit = false;
                    currentMapItem.InnerText = "查看相关信息";

                    txtTitle.Enabled = false;
                    txtUrl.Enabled = false;
                    chkCapabilities.Enabled = false;
                    chkIndustryFocus.Enabled = false;
                    chkGlobal.Enabled = false;
                    chkIndustry.Enabled = false;
                    chkClient.Enabled = false;
                    chkService.Enabled = false;

                    imgBtnConfirm.Visible = false;
                    imgBtnReset.Visible = false;


                    foreach (TableRow row in tblCaseStudy.Rows)
                    {
                        foreach (TableCell cell in row.Cells)
                        {
                            ItemShowing item = (ItemShowing)cell.Controls[0];
                            item.IsEnable = false;
                        }
                    }
                }
            }
            else
            {
                isEdit = false;
                isNew = true;
                currentMapItem.InnerText = "新建相关信息";
            }

            if (!IsPostBack)
            {
                BindCaseStudyInfo(isNew);
            }

            ViewState.Add("IsGlobal", chkGlobal.Checked.ToString().ToLower());
        }

        protected void imgBtnReset_Click(object sender, EventArgs e)
        {
            divReminding.InnerHtml = "";
            divReminding.Visible = false;

            if (!isEdit)
            {
                divReminding.InnerHtml = "";
                divReminding.Visible = false;

                txtTitle.Text = string.Empty;
                txtUrl.Text = string.Empty;
                chkCapabilities.Checked = false;
                chkIndustryFocus.Checked = false;
                chkGlobal.Checked = false;
                chkIndustry.Checked = false;
                chkClient.Checked = false;
                chkService.Checked = false;
            }
            else
            {
                BindData();
            }
        }

        protected void imgBtnConfirm_Click(object sender, EventArgs e)
        {
            if (!ValidateDates())
                return;

            string category = "";
            if (chkIndustry.Checked)
            {
                category += "industry;";
            }

            if (chkClient.Checked)
            {
                category += "client;";
            }

            if (chkService.Checked)
            {
                category += "service;";
            }
            
            RelatedInfo relatedInfo = new RelatedInfo();
            relatedInfo.Title = HttpUtility.HtmlEncode(txtTitle.Text);
            relatedInfo.Url = HttpUtility.HtmlEncode(txtUrl.Text);
            relatedInfo.IsCapability = chkCapabilities.Checked;
            relatedInfo.IsIndustryFocus = chkIndustryFocus.Checked;
            relatedInfo.IsGlobal = chkGlobal.Checked;
            relatedInfo.Category = category;
            relatedInfo.ModifyTime = DateTime.Now;

            relatedInfo.CaseStudies = hiddenCSChosen.Value;

            string errorDescription = string.Empty;    
            int relatedInfoId = -1;
            if (!isEdit)
            {
                if (!RelatedInformationBLL.Insert(relatedInfo, out errorDescription, out relatedInfoId))
                {
                    divReminding.InnerHtml = errorDescription;
                    divReminding.Visible = true;
                    divReminding.Style.Add("color", "Red");
                }
            }
            else
            {
                relatedInfo.Id = id;
                if (RelatedInformationBLL.Update(relatedInfo, out errorDescription))
                {
                    divReminding.InnerHtml = "修改相关信息成功！";
                    divReminding.Visible = true;
                    divReminding.Style.Add("color", "Green");
                }
                else
                {
                    divReminding.InnerHtml = errorDescription;
                    divReminding.Visible = true;
                    divReminding.Style.Add("color", "Red");
                }
            }

            BindCaseStudyInfo(relatedInfo.CaseStudies);

            if (relatedInfoId > 0)
            {
                string navgationUrl = string.Format("RelatedInfoDetail.aspx?id={0}&mode=edit&from=add", relatedInfoId.ToString());
                Response.Redirect(navgationUrl);
            }
        }

        protected void imgBtnReturn_Click(object sender, EventArgs e)
        {
            Response.Redirect("RelatedInfoManager.aspx");
        }

        private void BindData()
        {
            RelatedInfo relatedInfo = RelatedInformationBLL.GetInfo(id);
            txtTitle.Text = HttpUtility.HtmlDecode(relatedInfo.Title);
            txtUrl.Text = HttpUtility.HtmlDecode(relatedInfo.Url);
            chkCapabilities.Checked = relatedInfo.IsCapability;
            chkIndustryFocus.Checked = relatedInfo.IsIndustryFocus;
            chkGlobal.Checked = relatedInfo.IsGlobal;

            string category = relatedInfo.Category.ToLower();
            string[] categories = category.Split(new char[] { ';' });

            List<string> list = new List<string>();
            foreach (string s in categories)
            {
                if (!string.IsNullOrEmpty(s))
                {
                    list.Add(s);
                }
            }

            if (list.Contains("industry"))
            {
                chkIndustry.Checked = true;
            }

            if (list.Contains("client"))
            {
                chkClient.Checked = true;
            }

            if (list.Contains("service"))
            {
                chkService.Checked = true;
            }
        }

        private void BindCaseStudyInfo(bool isNew)
        {
            List<string> caseStudyIds;

            if (!isNew)
            {
                caseStudyIds = CaseStudyRelatedInformationBLL.GetInfoIdsByRelatedId(id);
            }
            else
            {
                caseStudyIds = new List<string>();
            }

            BindCaseStudy(caseStudyIds);
        }

        private void BindCaseStudyInfo(string caseStudies)
        {
            List<string> caseStudyIds = new List<string>();


            string tIds = caseStudies;
            string[] ids = tIds.Split(new char[] { ';' });

            foreach (string s in ids)
            {
                if (string.IsNullOrEmpty(s))
                    continue;

                caseStudyIds.Add(s);
            }

            BindCaseStudy(caseStudyIds);
        }

        private void BindCaseStudy(List<string> caseStudyIds)
        {
            tblCaseStudy.Rows.Clear();

            DataSet dataSet = CaseStudyBLL.GetAll();
            DataTable table = dataSet.Tables[0];
            int count = table.Rows.Count;

            TableRow row = new TableRow();
            TableCell cell;

            string results = string.Empty;
            string defaultIds = string.Empty;

            for (int i = 0; i < count; i++)
            {
                bool isCheck = false;

                string title = table.Rows[i]["Title"].ToString();


                ItemShowing caseStudy = new ItemShowing(isCheck, true, title, string.Empty);
                caseStudy.Id = table.Rows[i]["Id"].ToString();
                caseStudy.CssClass = "CSCss";

                if (caseStudyIds.Contains(caseStudy.Id))
                {
                    caseStudy.IsCheck = true;
                    results += table.Rows[i]["Title"] + ",";
                    defaultIds += caseStudy.Id + ";";
                }

                cell = new TableCell();

                cell.Controls.Add(caseStudy);
                cell.Style.Add("width", "200px");
                cell.Style.Add("padding", "5px");
                row.Cells.Add(cell);

                if (row.Cells.Count == 3)
                {
                    tblCaseStudy.Rows.Add(row);
                    row = new TableRow();
                    continue;
                }

                if ((count - i) == 1)
                {
                    tblCaseStudy.Rows.Add(row);
                }
            }

            defaultCaseStudies.Value = results;
            hiddenCSChosen.Value = defaultIds;
        }

        private bool ValidateDates()
        {
            if (string.IsNullOrEmpty(txtTitle.Text))
            {
                divReminding.InnerHtml = "标题不能为空！";
                divReminding.Style.Add("color", "Red");
                divReminding.Visible = true;
                return false;
            }

            if (HttpUtility.HtmlEncode(txtTitle.Text).Length > 99)
            {
                divReminding.InnerHtml = "标题太长了";
                divReminding.Style.Add("color", "Red");
                divReminding.Visible = true;
                return false;
            }

            if (string.IsNullOrEmpty(txtUrl.Text))
            {
                divReminding.InnerHtml = "链接地址不能为空！";
                divReminding.Style.Add("color", "Red");
                divReminding.Visible = true;
                return false;
            }

            if (HttpUtility.HtmlEncode(txtUrl.Text).Length > 199)
            {
                divReminding.InnerHtml = "链接地址太长了！";
                divReminding.Style.Add("color", "Red");
                divReminding.Visible = true;
                return false;
            }

            return true;
        }
    }
}
